@{
    ViewData["Title"] = "BOM详情";
}

<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />

<style>
    .bom-header {
        background: #f8f9fa;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
        border-left: 4px solid #5FB878;
    }
    
    .bom-title {
        font-size: 24px;
        font-weight: bold;
        color: #333;
        margin-bottom: 15px;
    }
    
    .bom-meta {
        display: flex;
        flex-wrap: wrap;
        gap: 30px;
        margin-bottom: 15px;
    }
    
    .meta-item {
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .meta-label {
        color: #666;
        font-weight: 500;
    }
    
    .meta-value {
        color: #333;
        font-weight: 600;
    }
    
    .bom-actions {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }
    
    .tab-content {
        padding: 20px 0;
    }
    
    .search-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 5px;
    }
    
    .search-input {
        width: 300px;
    }
    
    .table-container {
        background: white;
        border-radius: 5px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        overflow: hidden;
    }
    
    .pagination-container {
        padding: 15px;
        text-align: center;
        background: #f8f9fa;
    }
    
    .layui-form-item .layui-form-label {
        width: 120px;
    }
    
    .layui-form-item .layui-input-block {
        margin-left: 150px;
    }
    
    .detail-item {
        margin-bottom: 15px;
    }
    
    .detail-label {
        font-weight: bold;
        color: #555;
        width: 100px;
        display: inline-block;
    }
    
    .detail-value {
        color: #333;
    }
    
    .layui-table-cell {
        height: auto;
        overflow: visible;
        text-overflow: inherit;
        white-space: normal;
    }
</style>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <!-- BOM头部信息 -->
            <div class="bom-header">
                <div class="bom-title" id="bomTitle">加载中...</div>
                <div class="bom-meta">
                    <div class="meta-item">
                        <span class="meta-label">创建人:</span>
                        <span class="meta-value" id="creator">-</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">创建时间:</span>
                        <span class="meta-value" id="createTime">-</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">最后修改人:</span>
                        <span class="meta-value" id="updater">-</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">修改时间:</span>
                        <span class="meta-value" id="updateTime">-</span>
                    </div>
                </div>
                <div class="bom-actions">
                    <button class="layui-btn layui-btn-normal" onclick="EditBom()">
                        <i class="layui-icon layui-icon-edit"></i> 编辑
                    </button>
                    <button class="layui-btn layui-btn-danger" onclick="DeleteBom()">
                        <i class="layui-icon layui-icon-delete"></i> 删除
                    </button>
                    <button class="layui-btn layui-btn-primary" onclick="PrintBom()">
                        <i class="layui-icon layui-icon-print"></i> 打印
                    </button>
                    <button class="layui-btn layui-btn-warm" onclick="ExpandStructure()">
                        <i class="layui-icon layui-icon-set"></i> 展开结构
                    </button>
                </div>
            </div>



            <!-- 标签页 -->
            <div class="layui-tab layui-tab-brief" lay-filter="bomTab">
                <ul class="layui-tab-title">
                    <li class="layui-this" lay-id="bomInfo">BOM信息</li>
                    <li lay-id="bomComponents">BOM配件</li>
                    <li lay-id="processFlow">工艺流程</li>
                    <li lay-id="operationLog">操作记录</li>
                </ul>
                <div class="layui-tab-content">
                    <!-- BOM信息标签页 -->
                    <div class="layui-tab-item layui-show" id="bomInfo">
                        <div class="layui-card">
                            <div class="layui-card-header">
                                <i class="layui-icon layui-icon-diamond"></i> 基础信息
                            </div>
                            <div class="layui-card-body">
                                <div class="layui-row layui-col-space20">
                                    <div class="layui-col-md6">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">BOM编号</label>
                                            <div class="layui-input-block">
                                                <span class="detail-value" id="bomCode">-</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="layui-col-md6">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">BOM主题</label>
                                            <div class="layui-input-block">
                                                <span class="detail-value" id="bomTitleInput">-</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-row layui-col-space20">
                                    <div class="layui-col-md6">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">版本</label>
                                            <div class="layui-input-block">
                                                <span class="detail-value" id="version">-</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="layui-col-md6">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">成品名称</label>
                                            <div class="layui-input-block">
                                                <span class="detail-value" id="productsName">-</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-row layui-col-space20">
                                    <div class="layui-col-md6">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">产品编号</label>
                                            <div class="layui-input-block">
                                                <span class="detail-value" id="productsCode">-</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="layui-col-md6">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">规格型号</label>
                                            <div class="layui-input-block">
                                                <span class="detail-value" id="productsModel">-</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-row layui-col-space20">
                                    <div class="layui-col-md6">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">单位</label>
                                            <div class="layui-input-block">
                                                <span class="detail-value" id="productsUnit">-</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="layui-col-md6">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">品牌</label>
                                            <div class="layui-input-block">
                                                <span class="detail-value" id="brand">-</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-row layui-col-space20">
                                    <div class="layui-col-md6">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">是否默认版本</label>
                                            <div class="layui-input-block">
                                                <span class="detail-value" id="status">-</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="layui-col-md6">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">日产量</label>
                                            <div class="layui-input-block">
                                                <span class="detail-value" id="output">-</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                                        <div class="layui-form-item layui-form-text">
                            <label class="layui-form-label">备注</label>
                            <div class="layui-input-block">
                                <span class="detail-value" id="desc">-</span>
                            </div>
                        </div>
                            </div>
                        </div>
                    </div>

                    <!-- BOM配件标签页 -->
                    <div class="layui-tab-item" id="bomComponents">
                        <div class="search-bar">
                            <button class="layui-btn layui-btn-normal" onclick="ExportComponents()">
                                <i class="layui-icon layui-icon-export"></i> 导出
                            </button>
                            <div class="search-input">
                                <input type="text" id="componentSearch" class="layui-input" placeholder="请搜索">
                            </div>
                        </div>
                        <div class="table-container">
                            <table class="layui-table" lay-size="sm">
                                <thead>
                                    <tr>
                                        <th style="width:50px;"><input type="checkbox" lay-skin="primary" lay-filter="chkAllComponents"></th>
                                        <th style="width:60px;">序号</th>
                                        <th style="width:120px;">物品编号</th>
                                        <th style="width:150px;">物品名称</th>
                                        <th style="width:150px;">规格型号</th>
                                        <th style="width:80px;">单位</th>
                                        <th style="width:100px;">物品类型</th>
                                        <th style="width:100px;">最小库存</th>
                                        <th style="width:100px;">最大库存</th>
                                        <th style="width:100px;">当前库存</th>
                                        <th style="width:100px;">单价</th>
                                        <th style="width:80px;">状态</th>
                                        <th style="width:120px;">备注</th>
                                    </tr>
                                </thead>
                                <tbody id="componentsBody">
                                    <tr><td colspan="13" style="text-align:center;color:#999;">加载中...</td></tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="pagination-container" id="componentsPagination"></div>
                    </div>

                    <!-- 工艺流程标签页 -->
                    <div class="layui-tab-item" id="processFlow">
                        <div class="search-bar">
                            <button class="layui-btn layui-btn-normal" onclick="ExportProcessFlow()">
                                <i class="layui-icon layui-icon-export"></i> 导出
                            </button>
                            <div class="search-input">
                                <input type="text" id="processSearch" class="layui-input" placeholder="请搜索">
                            </div>
                        </div>
                        <div class="table-container">
                            <table class="layui-table" lay-size="sm">
                                <thead>
                                    <tr>
                                        <th style="width:50px;"><input type="checkbox" lay-skin="primary" lay-filter="chkAllProcess"></th>
                                        <th style="width:60px;">序号</th>
                                        <th style="width:120px;">工艺流程编号</th>
                                        <th style="width:150px;">工艺流程名称</th>
                                        <th style="width:100px;">加工顺序</th>
                                        <th style="width:100px;">负责人</th>
                                        <th style="width:120px;">所属部门</th>
                                        <th style="width:80px;">状态</th>
                                        <th style="width:120px;">备注</th>
                                    </tr>
                                </thead>
                                <tbody id="processBody">
                                    <tr><td colspan="9" style="text-align:center;color:#999;">加载中...</td></tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="pagination-container" id="processPagination"></div>
                    </div>

                    <!-- 操作记录标签页 -->
                    <div class="layui-tab-item" id="operationLog">
                        <div class="layui-card">
                            <div class="layui-card-header">
                                <i class="layui-icon layui-icon-log"></i> 操作记录
                            </div>
                            <div class="layui-card-body">
                                <div id="operationLogContent">
                                    <p style="text-align:center;color:#999;">暂无操作记录</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/layui/layui.js"></script>

<script>
    var bomId = 0;
    var bomDetail = null;
    var currentTab = 'bomInfo';

    $(function(){
        console.log('页面初始化开始');
        console.log('当前URL:', window.location.href);
        
        // 加载BOM详情
        loadBomDetail();

        // 绑定标签页切换事件
        layui.use(['element', 'layer'], function(){
            var element = layui.element;
            var layer = layui.layer;
            
            // 重新渲染标签页
            element.render('tab');
            
            element.on('tab(bomTab)', function(data){
                console.log('标签页切换:', data);
                if (data && data.elem) {
                    currentTab = data.elem.getAttribute('lay-id');
                    console.log('当前标签页:', currentTab);
                    
                    if (currentTab === 'bomComponents') {
                        loadComponents();
                    } else if (currentTab === 'processFlow') {
                        loadProcessFlow();
                    }
                }
            });
        });
    });

    // 加载BOM详情
    function loadBomDetail() {
        console.log('开始加载BOM详情');
        var bomId = getBomIdFromUrl();
        console.log('获取到的BOM ID:', bomId);
        
        if (!bomId) {
            console.error('未找到BOM ID');
            layer.msg('未找到BOM ID，请从BOM列表页面点击"查看"按钮访问', {icon: 2});
            
            // 显示错误信息
            $('#bomTitle').text('BOM ID缺失');
            $('#creator').text('请从BOM列表页面点击"查看"按钮');
            $('#createTime').text('或者手动设置localStorage.bomId');
            $('#updater').text('例如: localStorage.setItem("bomId", "1")');
            $('#updateTime').text('然后刷新页面');
            return;
        }

        console.log('开始调用API获取BOM详情，ID:', bomId);
        
        // 显示加载中
        layer.load(1, {shade: [0.3, '#000']});

        $.ajax({
            url: `http://localhost:5141/api/Bom/GetBomDetail`,
            type: 'GET',
            data: { id: bomId },
            success: function(res) {
                layer.closeAll('loading');
                console.log('API调用成功，返回数据:', res);
                
                if (res && res.code === 200 && res.data) {
                    bomDetail = res.data;
                    console.log('BOM详情数据:', bomDetail);
                    console.log('数据结构分析:');
                    console.log('- bomInfo:', bomDetail.bomInfo);
                    console.log('- BomInfo:', bomDetail.BomInfo);
                    console.log('- goodsList:', bomDetail.goodsList);
                    console.log('- GoodsList:', bomDetail.GoodsList);
                    console.log('- bomRelations:', bomDetail.bomRelations);
                    console.log('- flowList:', bomDetail.flowList);
                    console.log('- FlowList:', bomDetail.FlowList);
                    console.log('- bomFlowRelation:', bomDetail.bomFlowRelation);
                    
                    // 渲染各个部分
                    renderBomInfo();
                    renderComponents();
                    renderProcessFlow();
                    
                    console.log('所有数据渲染完成');
                } else {
                    console.error('API返回错误:', res);
                    layer.msg('加载BOM详情失败: ' + (res.message || '未知错误'), {icon: 2});
                }
            },
            error: function(xhr, status, error) {
                layer.closeAll('loading');
                console.error('API调用失败:', {xhr, status, error});
                layer.msg('网络请求失败: ' + error, {icon: 2});
            }
        });
    }

    // 渲染BOM基本信息
    function renderBomInfo() {
        if (!bomDetail) {
            console.error('BOM详情数据为空:', bomDetail);
            return;
        }

        // 根据实际数据结构获取BOM信息
        var bom = bomDetail.bomInfo || bomDetail.BomInfo || bomDetail;
        console.log('渲染BOM基本信息:', bom);
        
        if (!bom) {
            console.error('无法获取BOM信息');
            return;
        }
        
        // 头部信息
        $('#bomTitle').text(bom.bomTitle || bom.BOMTitle || '未设置标题');
        $('#creator').text(bom.creater || bom.Creater || '未知');
        $('#createTime').text(bom.createTime ? new Date(bom.createTime).toLocaleString('zh-CN') : '未知');
        $('#updater').text(bom.updater || bom.Updater || '未知');
        $('#updateTime').text(bom.updateTime ? new Date(bom.updateTime).toLocaleString('zh-CN') : '未知');

        // 基础信息表单
        $('#bomCode').text(bom.bomCode || bom.BOMCode || '-');
        $('#bomTitleInput').text(bom.bomTitle || bom.BOMTitle || '-');
        $('#version').text(bom.version || bom.Version || '-');
        $('#productsName').text(bom.productsName || bom.ProductsName || '-');
        $('#productsCode').text(bom.productsCode || bom.ProductsCode || '-');
        $('#productsModel').text(bom.productsModel || bom.ProductsModel || '-');
        $('#productsUnit').text(bom.productsUnit || bom.ProductsUnit || '-');
        $('#brand').text(bom.brand || bom.Brand || '-');
        $('#status').text(bom.status ? '是' : '否');
        $('#output').text(bom.output || bom.Output || 0);
        $('#desc').text(bom.desc || bom.Desc || '-');
        
        console.log('BOM基本信息渲染完成');
    }

    // 渲染配件列表
    function renderComponents() {
        if (!bomDetail) {
            console.error('BOM详情数据为空:', bomDetail);
            return;
        }

        // 根据实际数据结构获取配件列表
        var components = bomDetail.goodsList || bomDetail.GoodsList || bomDetail.bomRelations || [];
        console.log('渲染配件列表:', components);
        
        if (!Array.isArray(components)) {
            console.error('配件列表不是数组:', components);
            return;
        }
        
        var str = '';

        if (components.length > 0) {
            components.forEach(function(item, index) {
                // 处理不同的数据结构
                var goodsInfo = item.goodsinfo || item.Goodsinfo || item;
                
                str += `<tr>
                            <td><input type="checkbox" lay-skin="primary"></td>
                            <td>${index + 1}</td>
                            <td>${goodsInfo.goodsCode || goodsInfo.GoodsCode || ''}</td>
                            <td>${goodsInfo.goodsName || goodsInfo.GoodsName || ''}</td>
                            <td>${goodsInfo.goodsModel || goodsInfo.GoodsModel || ''}</td>
                            <td>${goodsInfo.unit || goodsInfo.Unit || ''}</td>
                            <td>${goodsInfo.goodsType || goodsInfo.GoodsType || ''}</td>
                            <td>${goodsInfo.minStock || goodsInfo.MinStock || 0}</td>
                            <td>${goodsInfo.maxStock || goodsInfo.MaxStock || 0}</td>
                            <td>${goodsInfo.stock || goodsInfo.Stock || 0}</td>
                            <td>${goodsInfo.price || goodsInfo.Price || 0}</td>
                            <td>${goodsInfo.status ? '<span class="layui-badge layui-bg-green">启用</span>' : '<span class="layui-badge layui-bg-gray">禁用</span>'}</td>
                            <td>${goodsInfo.remark || goodsInfo.Remark || ''}</td>
                        </tr>`;
            });
        } else {
            str = '<tr><td colspan="13" style="text-align:center;color:#999;">暂无配件数据</td></tr>';
        }

        $('#componentsBody').html(str);
        renderComponentsPagination(components.length);
        console.log('配件列表渲染完成');
    }

    // 渲染工艺流程列表
    function renderProcessFlow() {
        if (!bomDetail) {
            console.error('BOM详情数据为空:', bomDetail);
            return;
        }

        // 根据实际数据结构获取工艺流程列表
        var flows = bomDetail.flowList || bomDetail.FlowList || bomDetail.bomFlowRelation || [];
        console.log('渲染工艺流程列表:', flows);
        
        if (!Array.isArray(flows)) {
            console.error('工艺流程列表不是数组:', flows);
            return;
        }
        
        var str = '';

        if (flows.length > 0) {
            flows.forEach(function(item, index) {
                // 处理不同的数据结构
                var flowInfo = item.processFlow || item.ProcessFlow || item;
                
                str += `<tr>
                            <td><input type="checkbox" lay-skin="primary"></td>
                            <td>${index + 1}</td>
                            <td>${flowInfo.flowCode || flowInfo.FlowCode || ''}</td>
                            <td>${flowInfo.flowName || flowInfo.FlowName || ''}</td>
                            <td>${flowInfo.flowNumber || flowInfo.FlowNumber || ''}</td>
                            <td>${flowInfo.responsible || flowInfo.Responsible || ''}</td>
                            <td>${flowInfo.department || flowInfo.Department || ''}</td>
                            <td>${flowInfo.status ? '<span class="layui-badge layui-bg-green">启用</span>' : '<span class="layui-badge layui-bg-gray">禁用</span>'}</td>
                            <td>${flowInfo.remark || flowInfo.Remark || ''}</td>
                        </tr>`;
            });
        } else {
            str = '<tr><td colspan="9" style="text-align:center;color:#999;">暂无工艺流程数据</td></tr>';
        }

        $('#processBody').html(str);
        renderProcessPagination(flows.length);
        console.log('工艺流程列表渲染完成');
    }

    // 渲染配件分页
    function renderComponentsPagination(total) {
        if (total <= 5) {
            $('#componentsPagination').html('');
            return;
        }

        var totalPages = Math.ceil(total / 5);
        var html = `<span>共${total}项数据</span> `;
        html += `<select id="componentPageSize" style="margin:0 10px;">`;
        html += `<option value="5" selected>5条/页</option>`;
        html += `<option value="10">10条/页</option>`;
        html += `<option value="20">20条/页</option>`;
        html += `</select> `;
        
        html += `<div class="layui-box layui-laypage layui-laypage-default">`;
        for (var i = 1; i <= totalPages; i++) {
            if (i === 1) {
                html += `<span class="layui-laypage-curr"><em class="layui-laypage-em"></em><em>${i}</em></span>`;
            } else {
                html += `<a href="javascript:;" data-page="${i}">${i}</a>`;
            }
        }
        html += `</div>`;
        
        $('#componentsPagination').html(html);
    }

    // 渲染工艺流程分页
    function renderProcessPagination(total) {
        if (total <= 5) {
            $('#processPagination').html('');
            return;
        }

        var totalPages = Math.ceil(total / 5);
        var html = `<span>共${total}项数据</span> `;
        html += `<select id="processPageSize" style="margin:0 10px;">`;
        html += `<option value="5" selected>5条/页</option>`;
        html += `<option value="10">10条/页</option>`;
        html += `<option value="20">20条/页</option>`;
        html += `</select> `;
        
        html += `<div class="layui-box layui-laypage layui-laypage-default">`;
        for (var i = 1; i <= totalPages; i++) {
            if (i === 1) {
                html += `<span class="layui-laypage-curr"><em class="layui-laypage-em"></em><em>${i}</em></span>`;
            } else {
                html += `<a href="javascript:;" data-page="${i}">${i}</a>`;
            }
        }
        html += `</div>`;
        
        $('#processPagination').html(html);
    }

    // 加载配件数据
    function loadComponents() {
        if (bomDetail && bomDetail.GoodsList) {
            renderComponents();
        }
    }

    // 加载工艺流程数据
    function loadProcessFlow() {
        if (bomDetail && bomDetail.FlowList) {
            renderProcessFlow();
        }
    }

    // 编辑BOM
    function EditBom() {
        var bomId = getBomIdFromUrl();
        if (window.parent && window.parent.loadPage) {
            window.parent.loadPage(`/Bom/BomEdit?id=${bomId}`, '编辑BOM');
        } else {
            location.href = `/Bom/BomEdit?id=${bomId}`;
        }
    }

    // 删除BOM
    function DeleteBom() {
        layer.confirm('确认删除该BOM吗？删除后无法恢复！', {icon: 3, title: '提示'}, function(index) {
            // 这里调用删除API
            layer.close(index);
            layer.msg('删除功能待实现', {icon: 1});
        });
    }

    // 打印BOM
    function PrintBom() {
        window.print();
    }

    // 展开结构
    function ExpandStructure() {
        layer.msg('展开结构功能待实现', {icon: 1});
    }

    // 导出配件
    function ExportComponents() {
        layer.msg('导出功能待实现', {icon: 1});
    }

    // 导出工艺流程
    function ExportProcessFlow() {
        layer.msg('导出功能待实现', {icon: 1});
    }

    // 创建子BOM
    function CreateSubBom(goodsId) {
        layer.msg('创建子BOM功能待实现', {icon: 1});
    }



        

        

        

        


    // 获取BOM ID（主要从localStorage获取，这是正确的数据流）
    function getBomIdFromUrl() {
        // 方法1：从localStorage获取（主要方式，从BomList页面传递）
        var storedId = localStorage.getItem('bomId');
        if (storedId) {
            console.log('从localStorage获取到BOM ID:', storedId);
            return storedId;
        }
        
        // 方法2：从URL查询参数获取（备用方式）
        var urlParams = new URLSearchParams(window.location.search);
        var id = urlParams.get('id');
        
        if (id) {
            console.log('从URL查询参数获取到BOM ID:', id);
            return id;
        }
        
        // 方法3：从ViewBag获取（服务器端传递，备用方式）
        var viewBagId = '@ViewBag.BomId';
        if (viewBagId && viewBagId !== '') {
            console.log('从ViewBag获取到BOM ID:', viewBagId);
            return viewBagId;
        }
        
        console.log('无法获取BOM ID');
        console.log('localStorage.bomId:', storedId);
        console.log('URL查询参数id:', id);
        console.log('ViewBag.BomId:', viewBagId);
        return null;
    }
</script>
